﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using JX.Application;
using JX.Infrastructure.Common;
using JX.Infrastructure.Framework.Jwt;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace JXWebApi.Controllers
{
    [EnableCors("AnyPolicy")]//设置跨域处理的代理
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TokenController : Controller
    {
        private IAdminServiceApp _AdminService;
        public TokenController(IAdminServiceApp adminService)
        {
            _AdminService = adminService;
        }

		/// <summary>
		/// 通过用户名和密码，得到JwtToken
		/// </summary>
		/// <param name="username"></param>
		/// <param name="password"></param>
		/// <returns></returns>
		[HttpPost]
		public async Task<IActionResult> GetToken(string username, string password)
		{
			try
			{
				if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
				{
					return ReturnErrorMsg("用户名或密码不能为空");
				}
				var identityResult = await _AdminService.Login(username, password);
				if (!identityResult.IsSuccess)
				{
					return ReturnErrorMsg(identityResult.ErrorString);
				}
				JwtUserInfo jwtUserInfo = new JwtUserInfo();
				var sid = identityResult.User.FindFirst(ClaimTypes.Sid).Value;
				jwtUserInfo.Sid = DataConverter.CLng(sid);
				jwtUserInfo.Name = identityResult.User.FindFirst(ClaimTypes.Name).Value;
				jwtUserInfo.Role = identityResult.User.FindFirst(ClaimTypes.Role).Value;
				var jwtResult = JwtHelper.GetJwtResult(jwtUserInfo, ConfigHelper.GetAppSettingSection<JwtConfig>());
				return Json(jwtResult);
			}
			catch (Exception ex)
			{
				return ReturnErrorMsg(ex.Message);
			}
		}

		/// <summary>
		/// 通过RefreshToken，得到新的JwtToken
		/// </summary>
		/// <param name="token">RefreshToken</param>
		/// <param name="userID">用户ID</param>
		/// <returns></returns>
		[HttpPost]
		public IActionResult RefreshToken(string token, int userID)
		{
			try
			{
				if (string.IsNullOrEmpty(token) || userID <= 0)
				{
					return ReturnErrorMsg("token不存在或用户ID为0");
				}
				var jwtResult = JwtHelper.RefreshToken(token, userID, ConfigHelper.GetAppSettingSection<JwtConfig>());
				return Json(jwtResult);
			}
			catch (Exception ex)
			{
				return ReturnErrorMsg(ex.Message);
			}
		}

		/// <summary>
		/// 验证TOKEN
		/// </summary>
		/// <param name="token"></param>
		/// <returns></returns>
		[HttpPost]
		public IActionResult ValidateToken(string token)
		{
			try
			{
				if (string.IsNullOrEmpty(token))
				{
					return ReturnErrorMsg("token不存在");
				}
				List<Claim> Clims = null;
				var jwtResult = JwtHelper.ValidateToken(token, ConfigHelper.GetAppSettingSection<JwtConfig>(),out Clims);
				if (jwtResult)
				{
					List<object> result = new List<object>();
					foreach(var item in Clims)
					{
						var climsInfo = new { type = item.Type, value = item.Value };
						result.Add(climsInfo);
					}
					return Json(result);
				}
				else
				{
					return ReturnErrorMsg("验证失败");
				}
			}
			catch (Exception ex)
			{
				return ReturnErrorMsg(ex.Message);
			}
		}

		/// <summary>
		/// 得到当前登录用户的信息
		/// </summary>
		/// <returns></returns>
		[HttpPost]
		[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "SuperAdmin,AdministratorManage")]
		public IActionResult GetAdminInfo()
		{
			try
			{
				//当前登录用户的信息
				List<object> result = new List<object>();
				foreach (var item in User.Claims)
				{
					var climsInfo = new { type = item.Type, value = item.Value };
					result.Add(climsInfo);
				}
				return Json(new { Status = true, Msg = "", Data = JsonConvert.SerializeObject(result) });
			}
			catch (Exception ex)
			{
				return ReturnErrorMsg(ex.Message);
			}
		}

		/// <summary>
		/// 返回认证失败消息
		/// </summary>
		/// <param name="errMsg"></param>
		/// <returns></returns>
		private IActionResult ReturnErrorMsg(string errMsg)
		{
			return Json(new { Status = false, Msg = errMsg });
		}
	}
}